package com.ebupt.migu.music.schedule.service.impl;

import com.alibaba.fastjson.JSON;
import com.ebupt.migu.music.autoTri.Entity.PopupStatistics;
import com.ebupt.migu.music.common.util.DateUtil;
import com.ebupt.migu.music.redis.service.RedisService;
import com.ebupt.migu.music.schedule.mapper.PopupStatsMapper;
import com.ebupt.migu.music.schedule.service.KafkaDataService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.text.SimpleDateFormat;
import java.util.*;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;

@Slf4j
@Service
public class KafkaDataServiceImpl implements KafkaDataService {

    @Autowired
    private RedisService redisService;

    private static String POPUP_STATS_MIN = "POPUP_STATS_MIN";

    private static String POPUP_STATS_MIN_ACT = "POPUP_STATS_MIN_ACT";

    private static final String STATS_MIN = "00:00";

    private static final String END_MIN = "00:02";

    @Autowired
    private PopupStatsMapper popupStatsMapper;

    @Override
    public void deletePopupMinData() {
        if (isEffectiveDate()) {
            // 当前系统时间
            Date curdate = new Date();
            SimpleDateFormat formatDay = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            String dateString = formatDay.format(curdate);
            // 上周时间
            String lastweek = DateUtil.getSameDayOfLastWeek(dateString);
            popupStatsMapper.deleteBeforeRealtimeData(lastweek);
            log.info("变色龙实时计算表删除一周前的数据，具体时间为:{}", lastweek);
        }
    }

    @Override
    public void importPopupMinData() {
        // 获取实时更新的数据
        Set<Object> actSet = redisService.setMembers(POPUP_STATS_MIN_ACT);
        log.info("变色龙实时计算数据本轮更新的id集合:{}", actSet.toString());
        if (actSet != null && actSet.size() != 0 && isEffectiveDate()) {
            actSet.forEach((a) -> {
                String redisRealityMsi = "POPUP_STATS_MIN_MSI:" + a;
                String redisRealityMsiD = "POPUP_STATS_MIN_MSI_D:" + a;
                String redisExposureMsiD = "POPUP_MIN_EXP_MSI_D:" + a;
                String redisClickMsiD = "POPUP_MIN_CLI_MSI_D:" + a;
                String redisCloseMsiD = "POPUP_MIN_CLO_MSI_D:" + a;
                redisService.remove_key(redisRealityMsiD);
                redisService.remove_key(redisExposureMsiD);
                redisService.remove_key(redisClickMsiD);
                redisService.remove_key(redisCloseMsiD);
                log.info("实时计算actSet此时id为:{},有效时间:{}", a, redisService.getExpire(redisRealityMsi));
                redisService.remove_key(POPUP_STATS_MIN + ":" + a);
            });
            redisService.remove_key(POPUP_STATS_MIN_ACT);
            return;
        }
        if (actSet != null && actSet.size() != 0) {
            List<String> globalIds = new ArrayList<>();
            List<PopupStatistics> statsList = new ArrayList<>();
            // 通过活动id从redis中获取实时计算的数据
            actSet.forEach((s) -> {
                String actId = POPUP_STATS_MIN + ":" + s;
                String actType = "POPUP_STATS_MIN_TYPE:" + s;
                String redisRealityMsiD = "POPUP_STATS_MIN_MSI_D:" + s;
                String redisExposureMsiD = "POPUP_MIN_EXP_MSI_D:" + s;
                String redisClickMsiD = "POPUP_MIN_CLI_MSI_D:" + s;
                String redisCloseMsiD = "POPUP_MIN_CLO_MSI_D:" + s;

                Object redis = redisService.get(actId);
                if (null == redis) {
                    return;
                }
                PopupStatistics stats = JSON.parseObject(String.valueOf(redis), PopupStatistics.class);
                log.info("变色龙redis实时计算数据stats为:{}", stats);
                if (stats == null) {
                    return;
                }
                globalIds.add(stats.getActivityId());
                statsList.add(stats);
                // newStats = new PopupStatistics();
                PopupStatistics newStats = new PopupStatistics();
                BeanUtils.copyProperties(stats, newStats);
                newStats.setRealityCntsD(0);
                newStats.setExposureTimesD(0);
                newStats.setExposureCntsD(0);
                newStats.setClickTimesD(0);
                newStats.setClickCntsD(0);
                newStats.setCloseTimesD(0);
                newStats.setCloseCntsD(0);
                // 该处设值为了避免归零 三分钟数据时的数据错乱
                redisService.set(actType, "1");
                redisService.remove_key(actId);
                redisService.set(actId, JSON.toJSONString(newStats));
                sleepTime(100);
                redisService.set(actType, "0");

                redisService.remove_key(redisRealityMsiD);
                redisService.remove_key(redisExposureMsiD);
                redisService.remove_key(redisClickMsiD);
                redisService.remove_key(redisCloseMsiD);
                log.info("变色龙实时计算数据id为:{},value:{},newvValue:{}", stats.getActivityId(), newStats.toString());
            });
            if (statsList.size() == 0)
                return;
            // 通过活动id获取活动名称和执行类型（测试0还是正式1）
            List<Map<String, Object>> globalInfo = popupStatsMapper.queryActivityInfo(globalIds);
            statsList.forEach((sta) -> {
                globalInfo.forEach((global) -> {
                    if (sta.getActivityId().equals(global.get("activityId"))) {
                        sta.setActivityName((String)global.get("activityName"));
                        sta.setExeType((Integer)global.get("exeType"));
                    }
                });
            });
            // 过滤本地不存在的活动
            List<PopupStatistics> popList =
                statsList.stream().filter(sta -> sta.getActivityName() != null).collect(Collectors.toList());

            log.info("变色龙实时计算数据放入数据库:{}", statsList);
            log.info("实时计算实际存入数据库数据:{}", popList);
            // 将实时计算的数据插入数据表中
            int sqlnNum = popupStatsMapper.insertPopupRealtimeData(popList);
            log.info("变色龙实时计算数据放入数据库影响行数:{}", sqlnNum);
        }
    }

    public Object clone() {
        PopupStatistics statis = null;
        try {
            statis = (PopupStatistics)super.clone();
        } catch (CloneNotSupportedException e) {
            e.printStackTrace();
        }
        return statis;
    }

    private void sleepTime(long timeNum) {
        try {
            TimeUnit.MILLISECONDS.sleep(timeNum);
        } catch (InterruptedException e) {
            throw new RuntimeException(e);
        }
    }

    private boolean isEffectiveDate() {
        // 当前系统时间
        Date curdate = new Date();
        Date start = DateUtil.getSpecificTime(-1, 23, 59, 00);
        Date end = DateUtil.getSpecificTime(0, 0, 2, 00);
        return DateUtil.isEffectiveDate(curdate, start, end);
    }

    public static void main(String[] args) {
        Set<Integer> set = new HashSet<>();
        for (int i = 0; i <= 100; i++) {
            set.add(i);
        }
        set.forEach((s) -> {
            if (s == 10) {
                return;
            }
            System.out.println(s);
        });
    }
}
